Page({

  /**
   * 页面的初始数据
   */
  data: {
    historyList: [],
    value: '',
    hotList: [{
        id: 1,
        name: '谢宏宇隔扣詹姆斯',
        isHot: true
      },
      {
        id: 2,
        name: '安踏海沃德急速中国行',
        isHot: false
      },
      {
        id: 3,
        name: '奥尼尔',
        isHot: false
      },
      {
        id: 4,
        name: '湖人',
        isHot: false
      },
      {
        id: 5,
        name: '汤普森',
        isHot: false
      },
      {
        id: 6,
        name: '格林禁赛',
        isHot: false
      },
      {
        id: 7,
        name: '小贾伦-杰克逊获取DPOY',
        isHot: false
      },
      {
        id: 8,
        name: '维金斯',
        isHot: true
      },
      {
        id: 9,
        name: 'CBA季后赛',
        isHot: false
      },
    ],
    placeholderText: '请输入搜索内容'
  },
  onLoad: function (options) {
    // 获取历史搜索记录
    if (wx.getStorageSync('historyList')) {
      let his = wx.getStorageSync('historyList')
      this.setData({
        historyList: JSON.parse(his)
      })
    }
    // 轮训搜索历史
    var dynamiSearchs = setInterval(this.dynamiSearch, 3000)
  },
  // 确定搜索
  search(value) {
    if (value.currentTarget.dataset.value) {
      value.detail = value.currentTarget.dataset.value
    }

    let his = this.data.historyList
    //如果搜索内容为空，则搜索placeholderText的内容
    if (value.detail == '') {
      value.detail = self.data.placeholderText
    }
    if (his.length > 0) { // 如果不为空，则进行判断
      if (his.indexOf(value.detail) != -1) {
        his.splice(his.indexOf(value.detail), 1)
        his.unshift(value.detail)
      } else {
        his.unshift(value.detail)
      }
    } else { //否则直接添加
      his.unshift(value.detail)
    }
    if (his.length > 7) {
      his.pop()
    }
    // 对搜索内容进行存储
    wx.setStorageSync('historyList', JSON.stringify(his))
    this.setData({
      historyList: his
    })
  },
  // 清空搜索历史
  clearHistoryList() {
    wx.showModal({
      title: '确定删除全部搜索历史？',
      confirmColor: '#eb0e22',
      confirmText: '删除',
      complete: (res) => {
        if (res.confirm) { //确定
          wx.clearStorageSync('historyList')
          this.setData({
            historyList: []
          })
          wx.showToast({
            title: '删除成功！',
          })
        }
      }
    })
  },
  // 轮训热门搜索
  dynamiSearch() {
    const hotList = this.data.hotList
    let text = hotList[Math.floor(Math.random() * (hotList.length))].name
    this.setData({
      'placeholderText': text
    })
  }
})